﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Web.UI.WebControls;
using Controllerss;
using Core.Contract.DataContract;
using www.Controllers;
//using www.SService;

namespace www.Admin
{
    public partial class Staff : System.Web.UI.Page
    {
        #region Value
        //private readonly HyServicesClient _services = new HyServicesClient();
        private readonly LoginController _loginController=new LoginController();
        private readonly StaffController _staffController=new StaffController();
        private readonly ObjectCache _cache = MemoryCache.Default;
        static bool _insert = false;
        static int _id = 0;
        private readonly Utility _utility = new Utility();
        #endregion

        #region Contructor

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Convert.ToInt32(Session["role"]) != 1)
            {
                Message("Bạn không đủ quyền để thực hiện chức năng này.");
                Response.Redirect("Default.aspx");
            }
            if (Cache["Staff"] == null)
            {
                var lAdmin = _loginController.GetAllUser();
                if (lAdmin != null)
                    Cache.Insert("Staff", lAdmin.ToList(), null, DateTime.MaxValue, TimeSpan.FromDays(30));
            }
            if (!IsPostBack)
            {
                LoadData();
            }

        }
        #endregion

        #region Event

        protected void lbtinsert_Click(object sender, EventArgs e)
        {
            pnview.Visible = false;
            pncontrol.Visible = true;
            Donew();
            _insert = true;
            _id = 0;
            txtusername.Disabled = false;
            txtpassword.Disabled = false;
            txtrepassword.Disabled = false;
        }

        protected void lbtback_Click(object sender, EventArgs e)
        {
            try
            {
                Back();
            }
            catch (Exception)
            {

            }
        }

        protected void lbtrefresh_Click(object sender, EventArgs e)
        {
            try
            {
                LoadData();
            }
            catch (Exception)
            {

            }

        }

        protected void lbtdel_Click(object sender, EventArgs e)
        {
            try
            {
                Delete();
            }
            catch (Exception)
            {

            }

        }

        protected void grid_advertise_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                grid_staff.PageIndex = e.NewPageIndex;
                LoadData();
            }
            catch (Exception)
            {

            }
        }

        protected void grid_advertise_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                _id = Convert.ToInt32(e.CommandArgument);
                var lData = (List<RelaxStaffDataContract>)_cache["Employee"];
                if (lData == null)
                    return;
                var first = lData.FirstOrDefault(p => p.Id == _id);
                if (first == null)
                    return;
                if (e.CommandName == "cmd_edit")
                {

                    txtname.Value = first.Name;
                    txtbirthday.Text = first.Birthday.ToShortDateString();
                    ddlgender.SelectedValue = first.Gender.ToString();
                    fustaff.ResolveUrl(first.Image);
                    txtidentification.Value = first.Identification.ToString();
                    txttel.Value = first.Tel;
                    txtdegree.Value = first.Degree;
                    txtministry.Value = first.Ministry;
                    txtsalaryratio.Value = first.SalaryRatio.ToString();
                    txtsalary.Value = first.Salary.ToString();
                    txtallowance.Value = first.Allowance.ToString();
                    txthometown.Value = first.Hometown;
                    txtdatebegin.Text = first.DateBegin.ToShortDateString();
                    txtdateend.Text = first.DateEnd.ToShortDateString();
                    txtemail.Value = first.Email;
                    chkactive.Checked = first.Active == 1;

                    pncontrol.Visible = true;
                    pnview.Visible = false;
                    pndetaistaff.Visible = false;
                    _insert = false;

                }
                else if (e.CommandName == "cmd_delete")
                {
                    var lStaffUser = (List<RelaxLoginsDataContract>)Cache["Staff"];
                    if (lStaffUser != null)
                    {
                        var user = lStaffUser.FirstOrDefault(p => p.StaffId == _id);
                        if (user != null)
                        {
                            _loginController.DeleteLogin(user.Id);
                            lStaffUser.Remove(user);
                            Cache["Staff"] = lStaffUser;
                        }
                    }
                    if (_staffController.Delete(new List<long> { _id }))
                    {
                        Utilities.DeleteFile(Server.MapPath("~/" + first.Image));
                        lData.Remove(first);
                        _cache["Employee"] = lData;
                        LoadData();
                        Message("Xóa Thành Công");
                        _id = 0;
                    }
                    else
                    {
                        Message("Bạn phải hủy hết quyền hạn của nhân viên '" + first.Name + "' này mới có thể xóa nhân viên này");
                    }
                }
                else if (e.CommandName == "cmd_active")
                {
                    first.Active = first.Active == 1 ? 0 : 1;

                    _staffController.Update(first);
                    _cache["Employee"] = lData;
                    LoadData();
                    Message("Cập nhật Thành Công");
                    _id = 0;

                }
                else if (e.CommandName == "cmd_detail")
                {
                    Detail(_id);
                    pncontrol.Visible = false;
                    pnview.Visible = false;
                    pndetaistaff.Visible = true;
                }
            }
            catch (Exception)
            {

            }
        }

        protected void lbtsave_Click(object sender, EventArgs e)
        {
            try
            {
                Save();
            }
            catch (Exception)
            {

            }
        }

        protected void lbtdonew_Click(object sender, EventArgs e)
        {
            try
            {
                Donew();
            }
            catch (Exception)
            {

            }

        }

        #endregion

        #region Business

        private void Save()
        {
            try
            {

                if (string.IsNullOrEmpty(txtbirthday.Text) || string.IsNullOrEmpty(txtname.Value) ||
                    string.IsNullOrEmpty(txttel.Value) || string.IsNullOrEmpty(txtidentification.Value) ||
                    string.IsNullOrEmpty(ddlgender.SelectedValue))
                {
                    Message("Bạn phải nhập đầy đủ thông tin gợi ý trên");
                    return;
                }
                var lData = (List<RelaxStaffDataContract>)_cache["Employee"];

                var path = "Images/Staff/";
                var ac = chkactive.Checked ? 1 : 0;
                var postedfile = fustaff.PostedFile;//Request.Files["fuadvertise"];
                if (postedfile != null)
                {
                    var filename = postedfile.FileName;
                    if (!_insert)
                    {
                        if (lData == null)
                            return;
                        var first =
                            lData.FirstOrDefault(p => p.Id == _id);
                        if (first == null)
                            return;
                        var img = first.Image;
                        if (string.IsNullOrEmpty(filename))
                            path = first.Image;
                        else
                            path += filename;
                        if (!string.IsNullOrEmpty(txtpassword.Value))
                        {
                            if (txtpassword.Value != txtrepassword.Value)
                            {
                                Message("Mật khẩu không trùng nhau.");
                                return;
                            }
                            if (txtpassword.Value.Length < 6)
                            {
                                Message("Mật khẩu tối thiểu 6 ký tự.");
                                return;
                            }
                        }

                        var lStaffUser = (List<RelaxLoginsDataContract>)Cache["Staff"];
                        if (lStaffUser == null)
                            lStaffUser = new List<RelaxLoginsDataContract>();

                        if (!string.IsNullOrEmpty(txtpassword.Value) && !string.IsNullOrEmpty(txtusername.Value))
                        {
                            var user = lStaffUser.FirstOrDefault(p => p.StaffId == _id);
                            if (user != null)
                            {
                                user.UserName = txtusername.Value;
                                user.Password = _utility.Encrypt("Dragon_hy", txtpassword.Value);
                                user.Role = Convert.ToInt32(ddlRole.Value);
                                _loginController.UpdateLogin(user);
                                Cache["Staff"] = lStaffUser;
                            }
                            else
                            {
                                var login = new RelaxLoginsDataContract
                                {
                                    StaffId = _id,
                                    UserName = txtusername.Value,
                                    Password = _utility.Encrypt("Dragon_hy", txtpassword.Value),
                                    Active = 1,
                                    Role = Convert.ToInt32(ddlRole.Value)
                                };
                                var userId = _loginController.AddLogin(login);
                                login.Id = userId;
                                lStaffUser.Add(login);
                                Cache["Staff"] = lStaffUser;
                            }
                        }
                        var advertise = new RelaxStaffDataContract
                        {
                            Id = _id,
                            Active = ac,
                            Identification = Convert.ToInt32(txtidentification.Value),
                            Tel = txttel.Value,
                            Birthday = Convert.ToDateTime(txtbirthday.Text),
                            Gender = Convert.ToInt32(ddlgender.SelectedValue),
                            Degree = txtdegree.Value,
                            Ministry = txtministry.Value,
                            Salary = (float)Math.Round(float.Parse(string.IsNullOrEmpty(txtsalary.Value) ? "0" : txtsalary.Value), 2),
                            SalaryRatio = (float)Math.Round(float.Parse(string.IsNullOrEmpty(txtsalaryratio.Value) ? "0" : txtsalaryratio.Value), 2),
                            Allowance = (float)Math.Round(float.Parse(string.IsNullOrEmpty(txtallowance.Value) ? "0" : txtallowance.Value), 2),
                            Hometown = txthometown.Value,
                            DateBegin = string.IsNullOrEmpty(txtdatebegin.Text) ? DateTime.Now : Convert.ToDateTime(txtdatebegin.Text),
                            DateEnd = string.IsNullOrEmpty(txtdateend.Text) ? DateTime.Now : Convert.ToDateTime(txtdateend.Text),
                            Email = txtemail.Value,
                            Image = path,
                            Name = txtname.Value
                        };

                        if (_staffController.Update(advertise))
                        {
                            if (!string.IsNullOrEmpty(filename))
                            {
                                Utilities.DeleteFile(Server.MapPath("~/" + img));
                                postedfile.SaveAs(Server.MapPath("~/" + path));
                            }
                            var firstordefault = lData.FirstOrDefault(p => p.Id == _id);
                            if (firstordefault != null)
                            {
                                firstordefault.Name = advertise.Name;
                                firstordefault.Image = advertise.Image;
                                firstordefault.Identification = advertise.Identification;
                                firstordefault.DateBegin = advertise.DateBegin;
                                firstordefault.DateEnd = advertise.DateEnd;
                                firstordefault.Birthday = advertise.Birthday;
                                firstordefault.Active = advertise.Active;
                                firstordefault.Allowance = advertise.Allowance;
                                firstordefault.Degree = advertise.Degree;
                                firstordefault.Ministry = advertise.Ministry;
                                firstordefault.Email = advertise.Email;
                                firstordefault.Gender = advertise.Gender;
                                firstordefault.Hometown = advertise.Hometown;
                                firstordefault.Tel = advertise.Tel;
                                firstordefault.Salary = advertise.Salary;
                                firstordefault.SalaryRatio = advertise.SalaryRatio;

                            }

                            _cache["Employee"] = lData;
                            Message("Sửa Thành Công !");
                            _id = 0;
                            txtusername.Disabled = true;

                            pncontrol.Visible = false;
                            pnview.Visible = true;
                        }
                        else
                        {
                            Message("Không có bản ghi nào được cập nhật !");
                        }
                    }
                    else
                    {
                        var lStaffUser = (List<RelaxLoginsDataContract>)Cache["Staff"];
                        if (lStaffUser == null)
                        {
                            lStaffUser = new List<RelaxLoginsDataContract>();
                        }
                        if (string.IsNullOrEmpty(filename))
                        {
                            Message("Ảnh không được bỏ trống.");
                            return;
                        }
                        if (string.IsNullOrEmpty(txtusername.Value))
                        {
                            Message("Tên đăng nhập không được để trống.");
                            return;
                        }
                        if (string.IsNullOrEmpty(txtpassword.Value))
                        {
                            Message("Mật khẩu không được để trống.");
                            return;
                        }
                        if (txtpassword.Value != txtrepassword.Value)
                        {
                            Message("Mật khẩu không trùng nhau.");
                            return;
                        }
                        var check = lStaffUser.Any(p => p.UserName == txtusername.Value);
                        if (check)
                        {
                            Message("Tên đăng nhập đã tồn tại.");
                            return;
                        }
                        path += filename;

                        var advertise = new RelaxStaffDataContract
                        {
                            Active = ac,
                            Identification = Convert.ToInt32(txtidentification.Value),
                            Tel = txttel.Value,
                            Birthday = Convert.ToDateTime(txtbirthday.Text),
                            Gender = Convert.ToInt32(ddlgender.SelectedValue),
                            Degree = txtdegree.Value,
                            Ministry = txtministry.Value,
                            Salary = (float)Math.Round(float.Parse(string.IsNullOrEmpty(txtsalary.Value) ? "0" : txtsalary.Value), 2),
                            SalaryRatio = (float)Math.Round(float.Parse(string.IsNullOrEmpty(txtsalaryratio.Value) ? "0" : txtsalaryratio.Value), 2),
                            Allowance = (float)Math.Round(float.Parse(string.IsNullOrEmpty(txtallowance.Value) ? "0" : txtallowance.Value), 2),
                            Hometown = txthometown.Value,
                            DateBegin = string.IsNullOrEmpty(txtdatebegin.Text) ? DateTime.Now : Convert.ToDateTime(txtdatebegin.Text),
                            DateEnd = string.IsNullOrEmpty(txtdateend.Text) ? DateTime.Now : Convert.ToDateTime(txtdateend.Text),
                            Email = txtemail.Value,
                            Image = path,
                            Name = txtname.Value
                        };

                        var lId = _staffController.Add(advertise);
                        advertise.Id = lId;

                        var login = new RelaxLoginsDataContract
                        {
                            StaffId = lId,
                            UserName = txtusername.Value,
                            Password = _utility.Encrypt("Dragon_hy", txtpassword.Value),
                            Active = 1,
                            Role = Convert.ToInt32(ddlRole.Value)
                        };
                        var userId = _loginController.AddLogin(login);
                        login.Id = userId;
                        lStaffUser.Add(login);
                        Cache["Staff"] = lStaffUser;

                        if (lData == null)
                            lData = new List<RelaxStaffDataContract>();
                        lData.Add(advertise);
                        _cache["Employee"] = lData;
                        postedfile.SaveAs(Server.MapPath("~/" + path));
                        LoadData();
                        Message("Thêm Thành Công !");
                    }
                }
                else
                {
                    Message("Bạn phải chọn ảnh !");
                }

            }
            catch (Exception ex)
            {
                Message(ex.Message);
            }
        }
        private void Back()
        {
            pnview.Visible = true;
            pncontrol.Visible = false;
            pndetaistaff.Visible = false;
            _insert = false;
            _id = 0;
        }

        private void Detail(int id)
        {
            var lData = (List<RelaxStaffDataContract>)_cache["Employee"];
            var detail =
                from s in lData.Where(p => p.Id == id)
                select new { s.Active, s.Allowance, s.Birthday, s.DateBegin, s.DateEnd, s.Degree, s.Email, s.Gender, s.Hometown, s.Id, s.Identification, s.Image, s.Ministry, s.Name, s.Salary, s.SalaryRatio, s.Tel };
            frvstaff.DataSource = detail;
            frvstaff.DataBind();
        }
        private void Delete()
        {
            try
            {
                var lStaffUser = (List<RelaxLoginsDataContract>)Cache["Staff"];
                if (grid_staff.Rows.Count <= 0) return;
                var hang = 0;
                var lAd = new List<long>();
                for (var i = 0; i < grid_staff.Rows.Count; ++i)
                {
                    var chkselect = ((CheckBox)grid_staff.Rows[i].FindControl("chkselect")).Checked;
                    if (chkselect)
                    {
                        var id = ((Label)grid_staff.Rows[i].FindControl("lblid")).Text;
                        lAd.Add(Convert.ToInt32(id));
                    }
                }
                if (lStaffUser != null)
                {
                    foreach (var staffId in lAd)
                    {
                        var user = lStaffUser.FirstOrDefault(p => p.StaffId == staffId);
                        if (user != null)
                        {
                            _loginController.DeleteLogin(user.Id);
                            lStaffUser.Remove(user);
                        }
                    }
                    Cache["Staff"] = lStaffUser;
                }

                if (_staffController.Delete(lAd))
                {
                    var lData = (List<RelaxStaffDataContract>)_cache["Employee"];
                    if ((lData.Any()))
                    {
                        foreach (var id in lAd)
                        {
                            var first = lData.FirstOrDefault(p => p.Id == id);
                            if (first != null)
                            {
                                lData.Remove(first);
                                hang++;
                            }
                        }
                    }
                    LoadData();
                    if (hang != 0)
                    {
                        Message("Có " + hang + "bản ghi được Xóa Thành Công");
                    }
                    else
                    {
                        Message("Không có bản ghi nào được xóa !");
                    }
                }
                else
                {
                    Message("bạn phải hủy bỏ quyền của những nhân viên này trước khi xóa.");
                }

            }
            catch { }
        }
        public void LoadData()
        {
            if (_cache["Employee"] == null)
            {
                var lData = _staffController.GetStaffDataContracts().ToList();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                    _cache.Set("Employee", lData, policy);

                    grid_staff.DataSource = lData;
                    grid_staff.DataBind();
                }
            }
            else
            {
                var lData = (List<RelaxStaffDataContract>)_cache["Employee"];

                grid_staff.DataSource = lData.ToList();
                grid_staff.DataBind();
            }
        }
        private void Donew()
        {
            chkactive.Checked = false;
            txtname.Value = "";
            txtallowance.Value = "";
            txtbirthday.Text = "";
            txtdatebegin.Text = "";
            txtdateend.Text = "";
            txtdegree.Value = "";
            txtemail.Value = "";
            txthometown.Value = "";
            txtidentification.Value = "";
            txtministry.Value = "";
            txtpassword.Value = "";
            txtrepassword.Value = "";
            txtsalary.Value = "";
            txtsalaryratio.Value = "";
            txttel.Value = "";
            txtusername.Value = "";
            txtname.Focus();
        }
        private void Message(string str)
        {
            Response.Write("<script>alert('" + str + "');</script>");
        }
        #endregion
    }
}